package com.laowang.blog.provider;

import com.laowang.blog.exception.CustomizeErrorCode;
import com.laowang.blog.exception.CustomizeException;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;

@Component
public class QCloudProvider {

    @Value("${qCloud.qFile.secret-id}")
    private String secretId;
    @Value("${qCloud.qFile.secret-key}")
    private String secretKey;
    @Value("${qCloud.qFile.bucket-name}")
    private String bucketName;
    @Value("${qCloud.qFile.app-id}")
    private String appId;
    @Value("${qCloud.qFile.region}")
    private String regionName;
    @Value("${qCloud.qFile.key}")
    private String key;

    public String upload(InputStream fileStream,String mineType,String fileName){
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(regionName);
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);


        // 指定要上传的文件
        String generateFileName="";
        String[] filePaths = fileName.split("\\.");
        if(filePaths.length>1){
            generateFileName = UUID.randomUUID().toString()+"."+filePaths[filePaths.length-1];
        }else {
            throw new CustomizeException(CustomizeErrorCode.FILE_UPLOAD_FAIL);
        }

        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(mineType);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName+"-"+appId, key,fileStream, metadata);
        PutObjectResult response = cosClient.putObject(putObjectRequest);
//        if (response != null && response.getRequestId() !=null) {
//            String url = String.valueOf(cosClient.getObjectUrl(key,bucketName));
//            return url;
//        } else {
//            throw new CustomizeException(CustomizeErrorCode.FILE_UPLOAD_FAIL);
//        }
        return null;
    }
}
